<%@ page import="java.sql.*" %>
<%--
  Created by IntelliJ IDEA.
  User: My
  Date: 2020/11/22
  Time: 21:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    Class.forName("com.mysql.jdbc.Driver");  //驱动程序名
    String url = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=UTF-8"; //数据库名
    String username = "root";  //数据库用户名
    String password = "root";  //数据库用户密码
    Connection conn = null;  //连接状态
    // 解决乱码。数据库连接加上：?useUnicode=true&characterEncoding=UTF-8
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-type", "text/html;charset=UTF-8");
    try {
        conn = DriverManager.getConnection(url, username, password);

        if(conn != null){
            out.print("数据库连接成功！");
            out.print("<br />");
            String name = request.getParameter("name");
            String sex = request.getParameter("sex");
            System.out.print(name);
            Statement stmt = null;
            ResultSet rs = null;
            String sql = "SELECT *FROM test;";  //查询语句
            String insetSql = "insert into student(name,sex) values ('"+name+"','"+sex+"')";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            boolean flag = stmt.execute(insetSql);
            out.print("查询结果：<br />");
            out.print("保存结果："+flag);
            out.print("<br />");
            out.println("姓名"+"  "+"性别 "+"  "+"年龄");
            out.print("<br />");
            while (rs.next()) {
                out.println(rs.getString("name")+"   &nbsp  "+rs.getString("address")+"  &nbsp "+rs.getInt("age")); //将查询结果输出
            }
        }

        else{
            out.print("连接失败！");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
%>
<html>
<head>
    <title>保存学生信息</title>
</head>
<body>

</body>
</html>
